package UI;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

public class BackgroundMusicPlayer
{
    private Clip clip;

    public BackgroundMusicPlayer(String filePath)
    {
        try
        {
            // 从文件路径创建音频输入流
            AudioInputStream audioIn = AudioSystem.getAudioInputStream(new File(filePath));
            // 从音频输入流获取音频剪辑
            clip = AudioSystem.getClip();
            // 加载音频剪辑
            clip.open(audioIn);
            // 设置音频剪辑循环播放
            clip.loop(Clip.LOOP_CONTINUOUSLY);
        } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    public void startMusic()
    {
        if (clip != null && !clip.isRunning())
            clip.start();
    }
    public void stopMusic()
    {
        if (clip != null && clip.isRunning())
            clip.stop();
    }

}
